from flask import Flask
import os
from flask_login import LoginManager
from .models import UserDB, User
import sqlite3

login_manager = LoginManager()
user_db = UserDB()

def create_app():
    app = Flask(__name__, 
                template_folder=os.path.abspath('templates'))
    
    app.config['SECRET_KEY'] = 'your-secret-key'  # 更改为随机生成的密钥
    
    # 从配置文件加载路径
    from .file_manager import FileManager
    file_manager = FileManager()
    app.config['SOURCE_PATH'] = file_manager.ssh_manager.config["paths"]["source_path"]
    app.config['DESTINATION_PATH'] = file_manager.ssh_manager.config["paths"]["destination_path"]
    
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    
    from .routes import bp
    from .auth import auth_bp
    
    app.register_blueprint(bp)
    app.register_blueprint(auth_bp)
    
    return app

@login_manager.user_loader
def load_user(user_id):
    conn = sqlite3.connect(user_db.db_path)
    c = conn.cursor()
    c.execute('SELECT id, username, is_admin FROM users WHERE id = ?', (user_id,))
    user_data = c.fetchone()
    conn.close()
    
    if user_data:
        return User({
            'id': user_data[0],
            'username': user_data[1],
            'is_admin': user_data[2]
        })
    return None
